﻿using System;
using ControleRepresentanteSync.Logic;
using ControleRepresentanteSync.Logic.Models;

namespace ControleRepresentanteSync.Application.SimpleSync
{
    abstract class SearchableSelectionPresenter<TSelectionViewModel, TItem, TContract, TModel, TContentViewModel, TFullContract, TCodigoContract> : SimpleSyncSelectionPresenter<TSelectionViewModel, TItem, TContract, TModel, TContentViewModel, TFullContract, TCodigoContract>
        where TSelectionViewModel : ISearchableSelectionViewModel<TContentViewModel, TModel, TItem, TContract>
        where TContentViewModel : class, ISearchableContentViewModel<TModel, TItem, TContract>
        where TItem : ISimpleSycItem<TContract>
        where TModel : Searchable
    {
        protected SearchableSelectionPresenter(IWindow window, TSelectionViewModel viewModel, IJolitexRetriever jolitexRetriever, IContractsProvider contractsProvider, IViewModelFactory viewModelFactory, IUserInterfaceService userInterfaceService, ISyncServiceProvider syncServiceProvider)
            : base(window, viewModel, jolitexRetriever, contractsProvider, viewModelFactory, userInterfaceService, syncServiceProvider)
        {
            ViewModel.SearchRazaoSocial = String.Empty;
            ViewModel.SearchNomeFantasia = String.Empty;
            ViewModel.SearchCidade = String.Empty;
            ViewModel.SearchBairro = String.Empty;

            ViewModel.SearchChanged += ViewModelSearchChanged;
        }

        private void ViewModelSearchChanged(object sender, EventArgs e)
        {
            string razaoSocial = ViewModel.SearchRazaoSocial.ToLower();
            string nomeFantasia = ViewModel.SearchNomeFantasia.ToLower();
            string cidade = ViewModel.SearchCidade.ToLower();
            string bairro = ViewModel.SearchBairro.ToLower();

            SetToSync(x => x.RazaoSocial.ToLower().Contains(razaoSocial) &&
                           x.NomeFantasia.ToLower().Contains(nomeFantasia) &&
                           x.Cidade.ToLower().Contains(cidade) &&
                           x.Bairro.ToLower().Contains(bairro));
        }

        public override void Dispose()
        {
            base.Dispose();

            ViewModel.SearchChanged -= ViewModelSearchChanged;
        }
    }
}